package com.errui.controller;

import com.errui.dto.PaginationDto;
import com.errui.mapper.UserMapper;
import com.errui.model.User;
import com.errui.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author: Erruihhh
 * @Date: 2022/4/28
 * @Time: 22:14
 * @PROJECT_NAME: IndexController
 * @Description:
 */
@Controller
public class IndexController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private QuestionService questionService;

    @GetMapping("/")
    public String index(@RequestParam(name = "page", defaultValue = "1") Integer page, @RequestParam(name = "size", defaultValue = "2") Integer size, HttpServletRequest request, Model model) {
        Cookie[] cookies = request.getCookies();
        if (cookies !=null && cookies.length != 0){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("token")) {
                    String token = cookie.getValue();
                    User user = userMapper.findByToken(token);
                    if (user != null) {
                        request.getSession().setAttribute("user", user);
                    }
                    break;
                }
            }
        }
        PaginationDto pagination = questionService.list(page, size);
        model.addAttribute("pagination", pagination);
        return "index";
    }

}